package com.ruoyi.common.mytools;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.util.UUID;

public class FileUtils {
    /*
    根据文件所在路径下载文件
     */
    public static void download(HttpServletResponse response, String filePath) {
        File file = new File(filePath);
        // 取得文件名。
        String fileName = file.getName();
        System.out.println(fileName+"1111111111111111111111");
        InputStream fis = null;
        try {
//        URL url = new URL(filePath);
//        InputStream fis = url.openStream();
            fis = new FileInputStream(file);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload");// 设置强制下载不打开
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
//            response.setHeader("Content-Length", String.valueOf(file.length()));

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
            fis.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{

        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public static String downloadFile(HttpServletResponse response, String path) {
        if (path != null) {
            //设置文件路径
            File file = new File(path);
            String fileName = file.getName();
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }


    /**
     * 删除本地服务器图片
     * @param filePath     文件路径   去除https后 剩余的路径  images/firstclassimgs/b9649186-1643-4818-b019-beb7f3178eb8.png
     */
    public static String deleteLocalServerImage(String fileName){
        File file = new File("src/main/resources/static/images/screenShot/imgFile/"+fileName);
        try {
            boolean flag = file.delete(); // 删除照片
            if (flag) {
                return "删除成功";
            } else {
                return "删除失败！";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "图片不存在或其他异常！";
        }
    }



    /**
     * 获取图片名称
     * @param filePath
     */
    public static String extractFileNameFromUr1(String imageUr1l) throws MalformedURLException {
        URL url = new URL(imageUr1l);
        String path = url.getPath();
        return path.substring(path.lastIndexOf( '/') + 1);
    }





    /**
     * MultipartFile类型 转 File类型
     * @param multipartFile
     * @return
     */
    private static File transferToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0],"."+filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 上传文件
     */
    public static void uploadFileToServer(File file) throws IOException {
        if (ObjectUtils.isEmpty(file)) {
            System.out.println("文件是空的");
            return;
        }
        String filename = file.getName();// 文件的名字。
        /*File descFile = new File("\\static\\images\\uploadimg\\" + filename);//如果不确定位置可以使用绝对路径进行测试
        if (!descFile.exists()) {
            descFile.createNewFile();
        }*/
        try {
            // 文件保存
            // 上传文件/图像到指定文件夹（这里可以改成你想存放地址的相对路径）
            File savePos = new File("src/main/resources/static/images/uploadimg/");
            if(!savePos.exists()){  // 不存在，则创建该文件夹
                savePos.mkdir();
            }
            // 获取存放位置的规范路径
            String realPath = savePos.getCanonicalPath();
            System.out.println("存放目录"+realPath);
            System.out.println("文件名"+filename);
            System.out.println("全称:"+realPath +"\\"+ generateRandomFileName(filename));
            byte[] bFile = Files.readAllBytes(file.toPath());
            IOUtils.write(bFile, new FileOutputStream(new File(realPath+"\\" +generateRandomFileName(filename))));
        } catch (Exception e) {
            System.out.println("文件保存出现异常了");
            e.printStackTrace();
            return;
        }
        System.out.println("文件上传成功了");
    }




    /**
     * 上传文件
     * @param file     文件
     * @param fileName 新的随机文件名
     */
    public static String uploadFileToServer(MultipartFile file, String destPath,String absolutePath, String fileName) throws IOException {
        String RandonFileName=generateRandomFileName(fileName); //随机文件名
        //返回的相对路径 http://localhost/static/images/uploadimg/333/xxx-xxx-xxx.jpg
        String finalPath=MyConstant.ServerIP+absolutePath + RandonFileName;
        File dest = new File(destPath+RandonFileName); //存放路径
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            //保存文件
            file.transferTo(dest);
        } catch (Exception e) {
            e.getMessage();
        }
        return !ObjectUtils.isEmpty(finalPath)?finalPath:"图片路径不存在";
    }

    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static String generateRandomFileName(String fileName) {
        return UUID.randomUUID() + getSuffix(fileName);
    }



} //class End
